package com.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.defaults.DefaultSqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;

/**
 * 配置类充当一个工厂的角色
 * @author 罗俊华
 * @since 2023/10/26 20:41
 */
@Configuration
public class SqlConfig {

    /**
     * 配置类中用 @Bean 标注的方法相当于工厂方法
     * @return
     */
    @Bean(initMethod = "init") // bean 创建完成后要调用的bean中的方法，启用之后能看到日志 09:28:41.820 [main] INFO com.alibaba.druid.pool.DruidDataSource - {dataSource-1} inited
    public DruidDataSource dataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl("jdbc:mysql://localhost:3306/mysql");
        dataSource.setUsername("root");
        dataSource.setPassword("925925");
        return dataSource;
    }

    @Bean
    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) {

        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        return sqlSessionFactoryBean;
    }
}
